<?php
/**
 * User: @lose
 * Date: 2019-10-23
 * Time: 16:59
 */

namespace Frieza\Modules\Photo\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\Queue;
use Doraemon\model\AdmNoteOutlineLog;
use Doraemon\model\AdmNoteRemark;
use Doraemon\model\Member;
use Doraemon\model\Photos as dbPhoto;
use Doraemon\model\Photos as DbPhotos;
use Doraemon\model\TopicActivity;
use Doraemon\service\AdmNote;
use Doraemon\service\Photos;
use Doraemon\service\Videos\Videos as sVideos;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Form;
use Frieza\Modules\Photo\Extensions\Filter as SearchFilter;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\service\Note\NoteHandle;
use Doraemon\cache\Photos as cPhotos;

class BadPhotoCheckController extends Controller
{
    const PAGE_SIZE = 20;

    const MARKTAG_FILE = '/home/adm_rsync_dir/mark_tag.json';

    public function index(Request $request, Content $content)
    {

        $searchResult = SearchFilter::getSearchResultByParams($request, true);
        $total = $searchResult['total'];
        $ids = $searchResult['rows'];
        $photos = Photos::getPhotos($ids); // 通过id获取图片信息

        //用户信息
        $uids = empty($photos) ? [] : array_column($photos, 'uid');
        $user_infos = Member::getUserInfoByIds($uids);
        $user_infos_regular = [];
        if ($user_infos && is_array($user_infos)) {
            foreach ($user_infos as $user_info) {
                $user_infos_regular[$user_info['uid']] = $user_info;
            }
        }
        //话题信息
        $topic_ids = empty($photos) ? [] : array_column($photos, 'topic_activity_id');
        $topic_infos = TopicActivity::getByIds($topic_ids);
        $topic_infos_regular = [];
        if ($topic_infos && is_array($topic_infos)) {
            foreach ($topic_infos as $topic_info) {
                $topic_infos_regular[$topic_info['id']] = $topic_info;
            }
        }

        //log信息
        $logs = AdmNoteOutlineLog::getLogsByIds($ids);
        $logs_infos = [];
        if ($logs && is_array($logs)) {
            $tmp = array();
            foreach ($logs as $log) {
                $tmp[$log['note_id']][] = $log['log'];
            }
            if (is_array($tmp) && $tmp) {
                foreach ($tmp as $id => $item) {
                    $logs_infos[$id] = implode(",", $item);
                }
            }
        }

        //noteremark信息
        $note_remarks = $noteremarks = AdmNoteRemark::getNoteRemarkByNoteIds($ids);
        $note_remark_regular = [];
        if ($note_remarks && is_array($note_remarks)) {
            foreach ($note_remarks as $note_remark) {
                $note_remark_regular[$note_remark['note_id']] = $note_remark['remark'];
            }
        }

        $i = 1;
        foreach ($photos as &$info) {
            if (empty($info['id'])) {
                continue;
            }
            $info['photo_id'] = $info['id'];
            $info['id'] = $i;
            $info['user_info'] = $user_infos_regular[$info['uid']];
            $info['topic_info'] = $topic_infos_regular[$info['topic_activity_id']];
            $info['logs'] = $logs_infos[$info['photo_id']];
            $info['note_remark'] = $note_remark_regular[$info['photo_id']];
            if ($info['show_type'] == DbPhotos::SHOW_TYPE_VIDEO) {
                $videoInfo = sVideos::getVideoCoverInfoById($info['video_id']);
                $info['expand'] = $this->_getVideoExpand($videoInfo);
            } else {
                $picInfos = json_decode($info['pic_list'], true);
                $info['expand'] = $this->_getPicExpand($picInfos);
            }
            $info['expand'] .= $this->_getDivLine();
            $i++;
        }

        $options = [
            'perPage' => $request->input('per_page') ? : 20
        ];

        $gridModel = new pGridDataModel($photos, $total, $options);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {

            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();

            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->filter(function (Grid\Filter $filter) {
                SearchFilter::getFilter($filter, true);
            });

            $grid->column('photo_id', 'NOTE_ID')->expand(function ($model) {
                return $this->expand;
            }, true)->width(100);
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);

            $grid->column('remark', '图说')->display(function () {
                return "<strong>[标题]:</strong>{$this->title}<br><strong>[正文]:</strong>{$this->remark}";
            })->width(350);
            $grid->column('relation', '关联信息')->display(function () {
                if ($this->topic_activity_id) {
                    return "<a href='http://manage.haohaozhu.me/Admin/Photos/detail/photo_id/$this->photo_id' target='_blank' >" . $this->photo_id . "</a><br>发布时间：" . date('Y-m-d H:i:s', $this->addtime) . "<br>话题id：" . "<a href='http://manage.haohaozhu.me/Admin/Question/questionListNew/menuid/1012.html?id=$this->topic_activity_id' target='_blank' >" . $this->topic_activity_id . "</a>" . '<br>' . "话题标题：" . $this->topic_info['title'];
                } else {
                    return "<a href='http://manage.haohaozhu.me/Admin/Photos/detail/photo_id/$this->photo_id' target='_blank' >" . $this->photo_id . "</a><br>发布时间：" . date('Y-m-d H:i:s', $this->addtime);
                }
            })->width(200);
            $grid->column('admin_score', '操作')->display(function () {
                $class_normal = 'btn-defalut';
                $class_invisible = 'btn-defalut';
                $options_normal = "<button class='btn rollback $class_normal' data-id='$this->photo_id' data-type='normal'>".dbPhoto::LOW_REVIEW_DESC[dbPhoto::LOW_REVIEW_ROLLBACK]."</button><br><br>";
                $options_bad = '';
                if ($this->show_status != dbPhoto::SHOW_STATUS_INVISIBLE) {
                    $options_bad = "<button class='btn operate $class_invisible' data-id='$this->photo_id' data-type='invisible'>".dbPhoto::LOW_REVIEW_DESC[dbPhoto::LOW_REVIEW_INVISIBLE]."</button>";
                }


                return $options_normal . $options_bad;
            });

            $grid->column('logs', '审核日志')->display(function () {
                $logs = str_replace("\n", "<br>", $this->logs);
                return $logs;
            })->width(250);

        });

        Admin::script($this->operateScript());
        Admin::script($this->rollbackScript());
        Admin::script($this->imgScript());

        return $content
            ->header('note违规审核列表')
            ->row("<div style='position:fixed;z-index:10000;top:50px;left:35%;width:600px;height:600px;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='width:auto;height:auto;max-width:100%;max-height:100%;'></div>")
            ->body($listGrid);

    }

    private function _getVideoExpand($videoInfo)
    {
        $row = new Row();
        $row->column(4, "<video class='img-responsive container-fluid' src='{$videoInfo['basicInfo']['play_url_for_frieza']}' controls ></video>");
        $row->column(8, implode("", array_map(function ($snapshotImg) {
            return "<img class='img-responsive float-left center-block col-md-2' src='{$snapshotImg}'/>";
        }, $videoInfo['snapshot'])));
        $box = new Box('视频信息');
        $box->solid()->content($row->render());
        return $box->render();
    }

    private function _getPicExpand($picInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($picInfo) {
            $imgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $picInfo['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            return "<img class='img-responsive float-left center-block col-md-2' src='{$imgUrl}' />";
        }, $picInfos)));
        $box = new Box('图片信息');
        $box->solid()->content($row->render());
        return $box->render();
    }

    /**
     * 分割线
     * @return string
     */
    private function _getDivLine()
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }

    private function operateScript()
    {
        $url = route('photo.operate');
        return <<<SCRIPT
            $('.operate').click(function() {
                var _this = $(this);
                let noteId = $(this).data('id');
                let type = $(this).data('type');
                let url = '{$url}'
                
                
                let params = {note_id:noteId, type:type}
                
                $.post(url, params , function (e) {
                    if(e.code == 1) {
                        _this.addClass('btn-success');
                        _this.removeClass('btn-default');
                        _this.siblings('button').removeClass('btn-success');
                        _this.siblings('button').addClass('btn-default');
                        
                        //隐藏删除按钮
                        if(type == 'invisible') {
                            _this.hide();
                        }
                        
                        toastr.success(e.msg, null, {
                            timeOut : 1000
                        });  
                    } else {
                        toastr.error(e.msg, null, {
                            timeOut : 1000
                        });
                    }
                });
            });

SCRIPT;
    }

    public function imgScript()
    {
        return <<<SCRIPT
            $('.imgMoveDiv').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });

SCRIPT;
    }

    private function rollbackScript()
    {
        return <<<SCRIPT
            $('.rollback').unbind('click').click(function() {
                var _this = $(this);
                var note_id = $(this).data('id');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '回滚原因',
                    shadeClose: true,
                    shade: 0.9,
                    area: ['700px', '600px'],
                    content: 'rollbackReason/'+note_id,
                    end: function() {
                        $.ajax({type:"get",url:"checkRollback/"+note_id,success:function(code) {
                            if(code == 1) {
                                _this.addClass('btn-success');
                                _this.siblings('button').removeClass('btn-success');
                                _this.siblings('button').addClass('btn-default');
                            }
                        }})
                    }
                });
		    });
SCRIPT;
    }

    public function rollbackReason(\App\Admin\Extensions\WorkContent $content, $noteId)
    {
        $info = [
            'note_id' => $noteId,
            'reason' => AdmNoteOutlineLog::ROLLBACK_REASON_MISTRIAL,
            'quality' => dbPhoto::QUALITY_PENDING,
            'score' => 0,
        ];

        $form = new Form($info);
        $form->hidden('note_id');
        $form->hidden('quality', '质量');
        $form->hidden('score', '分数');
        $form->select('reason', '原因')->options(AdmNoteOutlineLog::ROLLBACK_REASON_DESC)->required();
        $form->action('/admin/photo/badphotocheck/rollback');
        $form->disableReset();

        return $content
            ->header('回滚原因')
            ->body($form->render());
    }

    public function checkRollback($noteId)
    {
        $quality = dbPhoto::get('quality', ['id' => $noteId]);
        if($quality == dbPhoto::QUALITY_PENDING) {
            return 1;
        }
        return 0;
    }

    public function rollback(Request $request)
    {
        $msg = '调整成功';
        try {
            $params = $request->all();
            $noteId = $params['note_id'];
            $reasonType = $params['reason'];

            $data = [
                'admin_score' => 0,
                'status' => DbPhotos::STATUS_UNTREATED,
                'show_status' => DbPhotos::SHOW_STATUS_PRIVATE_FLOW,
                'quality' => DbPhotos::QUALITY_PENDING,
                'edittime' => time()
            ];

            $rs = DbPhotos::updatePhotoById($noteId, $data);

            if ($rs) {
                // 修改note remark
                NoteHandle::remarkNote($noteId, AdmNoteRemark::REMARK_ALMOST_NORMAL, 1);
                // 添加操作日志
                AdmNote::auditLog($noteId, dbPhoto::QUALITY_PENDING, Admin::user()->name, AdmNoteOutlineLog::AUDIT_CHANNEL_LOW_NOTE, $reasonType);
                // 删除图片信息缓存
                cPhotos::delete($noteId);
                Queue::insertQueue('Photo/afterAudit', [
                    'photo_id' => $noteId,
                ]);
            }

        } catch (\Exception $e) {
            $msg = $e->getMessage();
        }

        $success = new MessageBag([
            'title' => $msg
        ]);
        return back()->with(compact('success'));
    }
}